using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace SceneEngine
{
    public class SceneReader : ContentTypeReader<Scene>
	{
        protected override Scene Read(
            ContentReader input, Scene existingInstance)
        {
            Scene scene = new Scene();

            Dictionary<string, BaseObject> baseObjects = ReadBaseObjects(input);

            if (baseObjects != null)
            {
                foreach (KeyValuePair<string, BaseObject> pair in baseObjects)
                    scene.Add(pair.Key, pair.Value);
            }

            return scene;
        }

        private Dictionary<string, BaseObject> ReadBaseObjects(ContentReader input)
        {
            Dictionary<string, BaseObject> baseObjects = new Dictionary<string, BaseObject>();

            int entityCount = input.ReadInt32();

            if (entityCount > 0)
            {
                for (int i = 0; i < entityCount; i++)
                {
                    string name = input.ReadString();
                    string assetPath = input.ReadString();

                    bool placeOnTerrain = input.ReadBoolean();

                    Vector3 position = input.ReadVector3();
                    Quaternion rotation = input.ReadQuaternion();
                    Vector3 scale = input.ReadVector3();

                    Model model = EngineGlobals.Content.Load<Model>(assetPath);

                    BaseObject entity = new BaseObject(name, model, position, rotation, scale);
                    entity.PlaceOnTerrain = placeOnTerrain;
                    baseObjects.Add(name, entity);
                }

                return baseObjects;
            }

            return null;
        }
	}
}
